package com.glfx.controller;

import com.github.houbb.opencc4j.util.ZhConverterUtil;
import com.glfx.utils.FileUtils;
import com.glfx.utils.SimpleConvertUtils;
import com.glfx.utils.StringUtils;
import nl.siegmann.epublib.domain.*;
import nl.siegmann.epublib.epub.EpubReader;
import nl.siegmann.epublib.epub.EpubWriter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 柧麟浮休
 * @date 2022/7/7
 */
public class EpubToSimpleController {

    public static boolean toSimple(String path) {
        try {
            //修改内容 文本和图片文字的 简体变成繁体
            Book modifyBook = modifyEpubNovel(path);

            File file = new File(path);
            String targetPath = file.getPath();
            targetPath = ZhConverterUtil.toSimple(targetPath);

            //生成新的epub文件
            boolean isGenerate = generateNewEpub(modifyBook, targetPath);
            if (!isGenerate) {
                System.out.println("生成失败");
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static Book modifyEpubNovel(String novelPath) throws Exception {
        File novelFile = new File(novelPath);
        EpubReader reader = new EpubReader();
        Book book = reader.readEpub(new FileInputStream(novelFile));

        /*头部修改*/
        Metadata metadata = book.getMetadata();
        ArrayList<String> titles = new ArrayList<>();
        titles.add(SimpleConvertUtils.multiplyToSimple(metadata.getFirstTitle()));
        //设置标题
        metadata.setTitles(titles);
        //设置描述
        List<String> descriptions = metadata.getDescriptions();
        descriptions = descriptions.stream().map(ZhConverterUtil::toSimple).collect(Collectors.toList());
        metadata.setDescriptions(descriptions);
        //设置语言
        metadata.setLanguage("zh_CN");

        //设置属性
        Map<String, String> metaAttributes = getMetaAttributes(metadata);
        metadata.setMetaAttributes(metaAttributes);
        book.setMetadata(metadata);

        //对目录进行 繁体转简体
        TableOfContents tableOfContents = book.getTableOfContents();
        List<TOCReference> tocReferences = tableOfContents.getTocReferences();
        for (TOCReference tocReference : tocReferences) {
            String title = tocReference.getTitle();
            tocReference.setTitle(ZhConverterUtil.toSimple(title));
        }
        tableOfContents.setTocReferences(tocReferences);
        book.setTableOfContents(tableOfContents);

        //将繁体图片和文字进行修改
        Spine spine = book.getSpine();
        List<SpineReference> spineReferences = spine.getSpineReferences();
        for (SpineReference spineReference : spineReferences) {
            Resource resource = spineReference.getResource();
            //源数据
            byte[] data = resource.getData();
            //单个str是html文件的文本版
            String htmlStr = StringUtils.bytes2Hex(data);
            //将文本的繁体转简体
            htmlStr = ZhConverterUtil.toSimple(htmlStr);
            resource.setData(htmlStr.getBytes(StandardCharsets.UTF_8));
            spineReference.setResource(resource);
        }
        spine.setSpineReferences(spineReferences);
        book.setSpine(spine);
        return book;
    }

    private static Map<String, String> getMetaAttributes(Metadata metadata) {
        Map<String, String> metaAttributes = new HashMap<>(10);
        metaAttributes.put("cover", metadata.getMetaAttribute("cover"));
        metaAttributes.put("calibre:series", ZhConverterUtil.toSimple(metadata.getMetaAttribute("calibre:series")));
        metaAttributes.put("calibre:title_sort", ZhConverterUtil.toSimple(metadata.getMetaAttribute("calibre:title_sort")));
        metaAttributes.put("Sigil version", metadata.getMetaAttribute("Sigil version"));
        metaAttributes.put("calibre:series_index", metadata.getMetaAttribute("calibre:series_index"));
        metaAttributes.put("calibre:author_link_map", ZhConverterUtil.toSimple(metadata.getMetaAttribute("calibre:author_link_map")));
        metaAttributes.put("updated:author", "glfx");
        return metaAttributes;
    }

    private static boolean generateNewEpub(Book modifyBook, String targetPath) {
        EpubWriter writer = new EpubWriter();
        try {
            File file = new File(targetPath);
            String parentPath = file.getParent() + "\\";
            String fileName = file.getName();
            String folderName = FileUtils.removeNumAndLetter(fileName) + "\\";
            targetPath = parentPath + folderName + fileName;
            file = new File(parentPath + folderName);
            if (file.isDirectory() || !file.exists()) {
                file.mkdirs();
            }
            writer.write(modifyBook, new FileOutputStream(targetPath));
            System.out.println(targetPath + "生成成功");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
